<template>
    <div class="count">
        <div class="shell">
            <!-- 注册 -->
            <div class="container b-container" ref="Bcontainer">
                <el-form class="form" id="a-form" ref="registerRef" :rules="registerRules" :model="zcForm">
                    <h2 class="form_title title">注册账号</h2>
                    <el-form-item prop="username">
                        <input type="text" class="form_input" placeholder="用户名" v-model="zcForm.username"
                            @blur="validateRegister('username')">
                    </el-form-item>
                    <el-form-item prop="password">
                        <input type="password" class="form_input" placeholder="密码" v-model="zcForm.password"
                            @blur="validateRegister('password')">
                    </el-form-item>
                    <el-form-item prop="password2">
                        <input type="password" class="form_input" placeholder="确认密码" v-model="zcForm.password2"
                            @blur="validateRegister('password2')">
                    </el-form-item>
                    <el-form-item prop="mobile">
                        <input type="text" class="form_input" placeholder="手机号" v-model="zcForm.mobile"
                            @blur="validateRegister('mobile')">
                    </el-form-item>
                    <el-form-item prop="sms_code">
                        <div class="login-code">
                            <input type="text" class="form_input1" placeholder="验证码" v-model="zcForm.sms_code"
                                @blur="validateRegister('sms_code')">
                            <el-button color="rgb(75,112,226)" style="flex: 1" @click="sendCode(zcForm.mobile)">
                                {{ isCountdown ? countdownText : '发送验证码' }}
                            </el-button>
                        </div>
                    </el-form-item>
                    <el-button class="switch_button button switch-btn" @click="registerSubmit">注册</el-button>
                </el-form>
            </div>
            <!-- 登录 -->
            <div class="container  a-container" ref="Acontainer">
                <el-form class="form" id="b-form" v-if="forgetShow" ref="loginrRef" :model="ruleForm"  :rules="rules">
                    <h2 class="form_title title">登录账号</h2>
                    <el-form-item prop="mobile">
                        <input type="text" class="form_input" v-model="ruleForm.mobile" placeholder="手机号" @change="validateLogin('mobile')">
                    </el-form-item>
                    <el-form-item prop="inputPassword">
                        <input type="password" class="form_input" v-model="ruleForm.inputPassword" placeholder="密码" @change="validateLogin('inputPassword')">
                    </el-form-item>
                    <el-button class="switch_button button switch-btn" @click="loginSubmit">登录</el-button>
                    <div class="forget_password" @click="forgetShow = false">忘记密码</div>
                </el-form>
                <el-form class="form" id="b-form" v-else :model="forgetForm" ref="forgetRef" :rules="forgetRules">
                    <h2 class="form_title title">找回密码</h2>
                    <el-form-item prop="mobile">
                        <input type="text" class="form_input" v-model="forgetForm.mobile" placeholder="手机号" @blur="validateForget('mobile')">
                    </el-form-item>
                    <el-form-item prop="sms_code">
                        <div class="login-code">
                            <input type="text" class="form_input1" placeholder="验证码" v-model="forgetForm.sms_code"
                                @blur="validateForget('sms_code')">
                            <el-button color="rgb(75,112,226)" style="flex: 1" @click="sendCode(forgetForm.mobile)">
                                {{ isCountdown ? countdownText : '发送验证码' }}
                            </el-button>
                        </div>
                    </el-form-item>
                    <el-form-item prop="inputPassword">
                        <input type="password" class="form_input" v-model="forgetForm.inputPassword" placeholder="新密码" @blur="validateForget('inputPassword')">
                    </el-form-item>
                    <el-button class="switch_button button switch-btn" @click="forgetSubmit">提交</el-button>
                    <div class="forget_password" @click="forgetShow = true">登录</div>
                </el-form>
            </div>

            <div class="switch" ref="switchCnt">
                <div class="switch_circle"></div>
                <div class="switch_circle switch_circle-t"></div>
                <div class="switch_container" ref="switchC1">
                    <h2 class="switch_title title" style="letter-spacing: 0;">智慧安全领导座舱</h2>
                    <p class="switch_description description">无账号请注册！！！</p>
                    <button class="switch_button button switch-btn" @click="shell">注 册</button>
                </div>

                <div class="switch_container is-hidden" ref="switchC2">
                    <h2 class="switch_title title" style="letter-spacing: 0;">智慧安全领导座舱</h2>
                    <p class="switch_description description">已有账号去登陆！！！</p>
                    <button class="switch_button button switch-btn" @click="shell">登 录</button>
                </div>
            </div>
        </div>

        <el-dialog v-model="registerDialogVisible" width="500" center>
            <el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-click="handleClick">
                <el-tab-pane label="已有公司" name="first">
                    <div>
                        <el-form :model="form" label-width="auto" style="max-width: 600px">

                            <el-form-item label="公司名称" label-position="left">
                                <el-select v-model="form.name" placeholder="选择公司">
                                    <el-option v-for="(item,index) in form.companyList" :key="index" :label="item.name" :value="item.id" />
                                    <!-- <el-option label="公司二" value="beijing" /> -->
                                </el-select>
                            </el-form-item>

                        </el-form>

                    </div>
                </el-tab-pane>
                <el-tab-pane label="注册公司" name="second">
                    <div>
                        <el-form :model="form" label-width="auto" style="max-width: 600px">
                            <el-form-item label="公司名称" label-position="left">
                                <el-input v-model="form.name" />
                            </el-form-item>

                            <el-form-item label="公司文件" label-position="left">
                                <!-- <el-upload v-model:file-list="fileList" class="upload-demo"
                                    action="https://maoyanxun.oss-cn-guangzhou.aliyuncs.com/2/"
                                    :on-change="handleChange">
                                    <el-button type="primary">选择文件</el-button>
                    
                                </el-upload> -->
                                <el-upload class="upload-demo" ref="upload" action :http-request="httpRequest"
                                    :before-upload="beforeUpload" :on-exceed="handleExceed" :limit="1">
                                    <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                                    <!-- <div slot="tip" class="el-upload__tip">只能上传.xlsx文件，且不超过5M</div> -->
                                </el-upload>

                            </el-form-item>
                        </el-form>

                    </div>
                </el-tab-pane>

            </el-tabs>


            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="selectCompany">
                        提交
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { JSEncrypt } from 'jsencrypt'
import { Base64 } from 'js-base64'
import { login, getMobiles, registerUser, loginKey,forgetPassword,loginStatus } from "@/api/login/index.js";
import { companyList, creatCompany,joinCompany } from "@/api/company/index.js";
import { ElMessage,genFileId } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
// import type { UploadProps, UploadUserFile } from 'element-plus'

const router = useRouter()
const route = useRoute()
const upload = ref()
const forgetShow = ref(true)
// 注册标识
let registerFlag = ref(false)
let switchCnt = ref(null)
let switchC1 = ref(null)
let switchC2 = ref(null)
let Acontainer = ref(null)
let Bcontainer = ref(null)
const registerRef = ref(null);
const registerDialogVisible = ref(false);
const forgetForm = ref({
    mobile:'',
    sms_code:'',
    new_password:'',
    inputPassword:'',
})
const forgetRef = ref(undefined)

//存放上传文件
let fileList = []
let form = ref({
    name: '',
    logo: '',
    companyList: [],
})
const httpRequest = (option) => {
    fileList.push(option.file)
}
// 替换上一次图片文件
const handleExceed = (files) => {
    fileList.unshift(files[0])  // fileList 头部添加一条  取数组第一项file
    upload.value.clearFiles()
    const file = files[0]
    file.uid = genFileId()
    upload.value.handleStart(file)
}
// 上传前处理
function beforeUpload(file) {
    let fileSize = file.size
    const FIVE_M = 5 * 1024 * 1024;
    //大于5M，不允许上传
    if (fileSize > FIVE_M) {
        this.$message.error("最大上传5M")
        return false
    }
    return true
}

const activeName = ref('first')
//注册
const zcForm = ref({
    username: undefined,
    password: undefined,
    password2: undefined,
    sms_code: undefined,
    mobile: undefined,
    profile_photo:1
})
// const handleChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
//     fileList.value = fileList.value.slice(-3)
// }
//登录ref
const ruleForm = ref({
    mobile: '',
    password: '',
    inputPassword:'',
})
const inputPassword = ref('');

//注册验证
const registerRules = reactive({
    mobile: [
        { required: true, message: '手机号不能为空', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '密码不能为空', trigger: 'blur' },
    ],
    password2: [
        { required: true, message: '确认密码不能为空', trigger: 'blur' },
    ],
    username: [
        { required: true, message: '用户名不能为空', trigger: 'blur' },
    ],
    sms_code: [
        { required: true, message: '验证码不能为空', trigger: 'blur' },
    ],
})

//登录验证
const rules = {
    mobile: [
        { required: true, message: '手机号不能为空', trigger: 'blur' },
    ],
    inputPassword: [
        { required: true, message: '密码不能为空', trigger: 'blur' },
    ],
}

// 找回密码验证
const forgetRules = {
    mobile: [
        { required: true, message: '手机号不能为空', trigger: 'blur' },
    ],
    sms_code: [
        { required: true, message: '验证码不能为空', trigger: 'blur' },
    ],
    inputPassword: [
        { required: true, message: '密码不能为空', trigger: 'blur' },
    ],
}
// 找回密码
const forgetSubmit = async () => {
    forgetRef.value.validate(async valid => {
        if (valid) {
            forgetForm.value.new_password = await getloginKey(forgetForm.value.inputPassword)
            forgetPassword(forgetForm.value).then(res => {
                if (res.status == 200) {
                    forgetShow.value = true
                    ElMessage.success('找回密码成功!')
                }
            })
        }
    })
}
const clearLocal = () => {
    localStorage.clear();
}
clearLocal()
const loginrRef = ref(undefined)
//登录接口
const loginSubmit = async () => {
    loginrRef.value.validate(async valid => {
        if (valid) {
            ruleForm.value.password = await getloginKey(ruleForm.value.inputPassword)
            login(ruleForm.value).then(res => {
                
                if (res.status == 200) {
                    loginStatus().then(res => {
                        if(res.data.company_list.length > 0){
                            const companyList =ref([]);
                            companyList.value = res.data.company_list;
                            //const company_list = JSON.stringify(res.data.company_list);
                            
                                                    //倒序循环删除，避免索引错乱问题
                            for (let i = companyList.value.length - 1; i >= 0; i--) {
                            if (!companyList.value[i].is_csuper) {
                                //   直接使用当前索引i删除，无需findIndex
                                companyList.value.splice(i, 1);
                            }
                            }
                            debugger;
                            localStorage.setItem('companys',JSON.stringify(companyList.value));
                            localStorage.setItem('company', companyList.value[0].company_id);
                            router.push({ path: '/index' })
                        }else{
                            if(res.data.past_due_company){
                                ElMessage.warning(res.data.past_due_company)
                            }else{
                                ElMessage.error('没有分配公司!')
                            }
                            
                        }
                        // localStorage.setItem('section', res.data.company_list[0].section_list[0].section_id);   
                    })
                    
                    localStorage.setItem('token', JSON.stringify(res.data.token))
                    localStorage.setItem('userId', JSON.stringify(res.data.user_id))
                    localStorage.setItem('username', JSON.stringify(res.data.username))
                }
            })
        }
    })
    // if (ruleForm.value.mobile == null || ruleForm.value.mobile == undefined || ruleForm.value.mobile == "") {
    //     ElMessage.error("手机号不能为空！！！")
    //     return
    // }
    // if (inputPassword.value == null || inputPassword.value == undefined || inputPassword.value == "") {
    //     ElMessage.error("密码不能为空！！！")
    //     return
    // }
    
}

// 获取公钥
const getloginKey = async (e) => {
    try {
        const res = await loginKey();
        if (res.status === 200) {
            let encryptor = new JSEncrypt();
            // 设置公钥
            encryptor.setPublicKey(res.data.public_key);
            let encryptedPassword = encryptor.encrypt(e);
            // 检查加密是否成功
            if (encryptedPassword) {
                // 进行下一步操作，例如发送到后端
                let encodePwd = Base64.encode(`${encryptedPassword}|${res.data.random_key}`)
                return encodePwd
            } else {
                ElMessage.error("密码加密失败!!!")
                return null
            }
        }
    } catch (error) {
        console.error("请求失败:", error);
        return null

    }
};

let getButtons = (e) => e.preventDefault()

//定时器
const isCountdown = ref(false);
const countdown = ref(null);

const countdownText = ref('');

// 发送验证码并启动倒计时
const sendCode = (e) => {
    if (e == null || e == undefined || e == "") {
        ElMessage.error("手机号不能为空！！！")
        return
    }
    // 这里添加发送验证码的逻辑，比如调用API
    getMobiles(e).then(res => {})
    // 切换为倒计时状态
    isCountdown.value = true;
    let countdownTime = 60;
    countdownText.value = `${countdownTime}s`;
    // 设置倒计时
    countdown.value = setInterval(() => {
        countdownTime--;
        countdownText.value = `${countdownTime}s`;
        if (countdownTime <= 0) {
            // 清除定时器
            clearInterval(countdown.value);
            countdown.value = null;
            // 重置状态
            isCountdown.value = false;
            countdownText.value = '';
        }
    }, 1000);

};

const validateRegister = (field) => {
    registerRef.value.validateField(field);
};
const validateLogin = (field) => {
    loginrRef.value.validateField(field);
};
const validateForget = (field) => {
    forgetRef.value.validateField(field);
};
// 获取公司列表
const getCompanyList = () => {
    companyList().then(res => {
        form.value.companyList = res.data.results
    })
}
// 提交公司信息
const selectCompany = () => {
    // 选择已有公司
    if (activeName.value == "first") {
        localStorage.setItem("company",form.value.name)
        joinCompany(form.value.name).then(res=>{
            if(res.status==200){
              ElMessage({
                message: "申请成功",
                type: "success",
              })
              registerDialogVisible.value = false
            }
        })
    } else {
        // 创建公司
        localStorage.setItem('commanyReg', 'reg')
        // 使用form表单的数据格式
        const params = new FormData()
        // 将上传文件数组依次添加到参数paramsData中
        params.append("logo", fileList[0])
        // 将输入表单数据添加到params表单中
        params.append('name', form.value.name)
        creatCompany(params).then(res => {
            if (res.status == 200) {
                fileList = []//集合清空
                form.value = {} //清空
                localStorage.clear()
                ElMessage({
                message: "创建成功",
                type: "success",
              })
                registerDialogVisible.value = false
            }

        })
    }

}
//注册
const registerSubmit = async () => {
    registerRef.value.validate(async valid => {
        if (valid) {
            registerUser(zcForm.value).then(res => {
                if (res.status == 200) {
                    registerFlag.value = true
                    // 查询公司列表
                    getCompanyList()
                    localStorage.setItem('token', JSON.stringify(res.data.token))
                    registerDialogVisible.value = true

                }
            })
        }
    })
}

// 注册/登录切换
const shell = (e) => {
    // 修改类名
    switchCnt.value.classList.add("is-gx");
    setTimeout(function () {
        switchCnt.value.classList.remove("is-gx");
    }, 1500)
    switchCnt.value.classList.toggle("is-txr");
    switchC1.value.classList.toggle("is-hidden");
    switchC2.value.classList.toggle("is-hidden");
    Acontainer.value.classList.toggle("is-txl");
    Bcontainer.value.classList.toggle("is-txl");
    Bcontainer.value.classList.toggle("is-z");
}


</script>

<style scoped>
.forget_password{
    margin-top: 20px;
    color: #817878;
    cursor: pointer;
}
.count {
    box-sizing: border-box;
    /* 字体无法选中 */
    user-select: none;

    width: 100%;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 12px;
    background-color: #ecf0f3;
    color: #a0a5a8;
}


.shell {
    position: relative;
    width: 1000px;
    min-width: 1000px;
    min-height: 600px;
    height: 600px;
    padding: 25px;
    background-color: #ecf0f3;
    box-shadow: 10px 10px 10px #d1d9e6, -10px -10px 10px #f9f9f9;
    border-radius: 12px;
    overflow: hidden;
}

/* 设置响应式 */
@media (max-width: 1200px) {
    .shell {
        transform: scale(0.7);
    }
}

@media (max-width: 1000px) {
    .shell {
        transform: scale(0.6);
    }
}

@media (max-width: 800px) {
    .shell {
        transform: scale(0.5);
    }
}

@media (max-width: 600px) {
    .shell {
        transform: scale(0.4);
    }
}

.container {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    top: 0;
    width: 600px;
    height: 100%;
    padding: 25px;
    background-color: #ecf0f3;
    transition: 1.25s;
}

.form {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    width: 100%;
    height: 100%;
}

.iconfont {
    margin: 0 5px;
    border: rgba(0, 0, 0, 0.5) 2px solid;
    border-radius: 50%;
    font-size: 25px;
    padding: 3px;
    opacity: 0.5;
    transition: 0.1s;
}

.iconfont:hover {
    opacity: 1;
    transition: 0.15s;
    cursor: pointer;
}

.form_input {
    width: 350px;
    height: 40px;
    margin: 4px 0;
    padding-left: 25px;
    font-size: 13px;
    letter-spacing: 0.15px;
    border: none;
    outline: none;
    background-color: #ecf0f3;
    transition: 0.25s ease;
    border-radius: 8px;
    box-shadow: inset 2px 2px 4px #d1d9e6, inset -2px -2px 4px #f9f9f9;
}


.form_input1 {
    flex: 9;
    height: 40px;
    margin: 4px 0;
    padding-left: 25px;
    font-size: 13px;
    letter-spacing: 0.15px;
    border: none;
    outline: none;
    background-color: #ecf0f3;
    transition: 0.25s ease;
    border-radius: 8px;
    box-shadow: inset 2px 2px 4px #d1d9e6, inset -2px -2px 4px #f9f9f9;
}

.form_input1:focus {
    box-shadow: inset 4px 4px 4px #d1d9e6, inset -4px -4px 4px #f9f9f9;
}


.form_input:focus {
    box-shadow: inset 4px 4px 4px #d1d9e6, inset -4px -4px 4px #f9f9f9;
}

.form_span {
    margin-top: 30px;
    margin-bottom: 12px;
}

.form_link {
    color: #181818;
    font-size: 15px;
    margin-top: 25px;
    border-bottom: 1px solid #a0a5a8;
    line-height: 2;
}

.title {
    font-size: 34px;
    font-weight: 700;
    line-height: 3;
    color: #181818;
    letter-spacing: 10px;
}

.description {
    font-size: 14px;
    letter-spacing: 0.25px;
    text-align: center;
    line-height: 1.6;
}

.button {
    width: 180px;
    height: 50px;
    border-radius: 25px;
    margin-top: 50px;
    font-weight: 700;
    font-size: 14px;
    letter-spacing: 1.15px;
    background-color: #4B70E2;
    color: #f9f9f9;
    box-shadow: 8px 8px 16px #d1d9e6, -8px -8px 16px #f9f9f9;
    border: none;
    outline: none;
}

.a-container {
    z-index: 100;
    left: calc(100% - 600px);
}

.b-container {
    left: calc(100% - 600px);
    z-index: 0;
}

.switch {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 400px;
    padding: 50px;
    z-index: 200;
    transition: 1.25s;
    background-color: #ecf0f3;
    overflow: hidden;
    box-shadow: 4px 4px 10px #d1d9e6, -4px -4px 10px #d1d9e6;
}

.switch_circle {
    position: absolute;
    width: 500px;
    height: 500px;
    border-radius: 50%;
    background-color: #ecf0f3;
    box-shadow: inset 8px 8px 12px #b8bec7, inset -8px -8px 12px #fff;
    bottom: -60%;
    left: -60%;
    transition: 1.25s;
}

.switch_circle-t {
    top: -30%;
    left: 60%;
    width: 300px;
    height: 300px;
}

.switch_container {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    position: absolute;
    width: 400px;
    padding: 50px 55px;
    transition: 1.25s;
}

.switch_button {
    cursor: pointer;
}

.switch_button:hover,
.submit:hover {
    box-shadow: 6px 6px 10px #d1d9e6, -6px -6px 10px #f9f9f9;
    transform: scale(0.985);
    transition: 0.25s;
}

.switch_button:active,
.switch_button:focus {
    box-shadow: 2px 2px 6px #d1d9e6, -2px -2px 6px #f9f9f9;
    transform: scale(0.97);
    transition: 0.25s;
}

.is-txr {
    left: calc(100% - 400px);
    transition: 1.25s;
    transform-origin: left;
}

.is-txl {
    left: 0;
    transition: 1.25s;
    transform-origin: right;
}

.is-z {
    z-index: 200;
    transition: 1.25s;
}

.is-hidden {
    visibility: hidden;
    opacity: 0;
    position: absolute;
    transition: 1.25s;
}

.is-gx {
    animation: is-gx 1.25s;
}

@keyframes is-gx {

    0%,
    10%,
    100% {
        width: 400px;
    }

    30%,
    50% {
        width: 500px;
    }
}

.login-code {
    display: flex;
    align-items: center;
    width: 375px;
    justify-content: space-between;
    gap: 10px;
}

::v-deep .el-dialog__headerbtn {
    display: none;
}
</style>